package ltd.followkba.page;


//

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.ArrayRes;

import com.kcbsdk.MyWorks.AWorksType;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import ltd.advskin.MRAM;
import ltd.advskin.MSKIN;
import ltd.advskin.base.BasePage;

import ltd.advskin.base.KcTypeListener;
import ltd.advskin.task.TaskFree;
import ltd.advskin.view.KcBtnProgress;
import ltd.advskin.view.KcHeaderView;
import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.R;
import ltd.followkba.W;
import ltd.followkba.task.App32;
import ltd.followkba.task.BDbsAccount;
import ltd.followkba.task.EditUtils;
import ltd.followkba.task.WorksQueue;
import main.MAPI;

import static ltd.advskin.MSKIN.MLOGE;
import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;
import static main.MAPI.mMyUtils;

public class AddTaskPage extends BasePage {
    private EditText etInputAdd;
    private TextView tvAnalysisAdd;
    private CheckBox[] cbAddTo;
    private KcBtnProgress kbtEnterAdd;
    private String gsAppName;
    private byte gWorksType;
    private byte[] mWorksType;
    private List<BDbsAccount> mBDbsAccount;



    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;

    public void MLOG(String text) {
        if (logEnable) {
            MSTRING(MAPI.GET_LOG_NAME(this) + text);
        }
    }

    @Override
    public void onInitView() {                       // 使用者需要继承，初始化页面控件等显示
        setLayout(R.layout.page_add_task);
        if (mBaseInput != null) {                   // 可能仅仅需要刷新，未必是重新开始的
            gsAppName = mBaseInput.getInput(0);
            gWorksType = mBaseInput.getInput(1);
            mBaseInput = null;                  // 输入参数的使命已经完成，记得及时销毁之
        }
        mKcHeaderView = findViewById(R.id.khvAdd);
        String text = String.format("添加%s账号", gsAppName);
        mKcHeaderView.setTitle(text, new KcTypeListener() {
            @Override
            public void onMessage(int type) {
                switch (type) {
                    case KcHeaderView.TYPE_CLICK_LEFT:
                        onFinish();
                        break;
                    case KcHeaderView.TYPE_CLICK_RIGHR:

                        break;
                }
            }
        });
        etInputAdd = findViewById(R.id.etInputAdd);
        tvAnalysisAdd = findViewById(R.id.tvAnalysisAdd);
        int[] tabCbAddTo = {R.id.cbAddTo0, R.id.cbAddTo1, R.id.cbAddTo2, R.id.cbAddTo3, R.id.cbAddTo4, R.id.cbAddTo5};
        cbAddTo = new CheckBox[tabCbAddTo.length];
        for (int index = 0; index < cbAddTo.length; index++){
            cbAddTo[index] = findViewById(tabCbAddTo[index]);
        }
        kbtEnterAdd = findViewById(R.id.kbtEnterAdd);
        findViewById(R.id.kbtPasteAdd).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {           // 粘贴
                // 获取系统剪贴板
                ClipboardManager clipboard = (ClipboardManager) MRAM.mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                // 返回数据
                ClipData clipData = clipboard.getPrimaryClip();
                if (clipData != null && clipData.getItemCount() > 0) {
                    // 从数据集中获取（粘贴）第一条文本数据
                    String text = clipData.getItemAt(0).getText().toString();
                    etInputAdd.setText(text);
                }
//                ClipboardManager clipboardManager = (ClipboardManager) MRAM.mContext.getSystemService(Context.CLIPBOARD_SERVICE);
//                ClipData clipData = clipboardManager.getPrimaryClip();
//                if (clipData != null) {
//                    ClipData.Item item = clipData.getItemAt(0);
//                    if (item != null) {
//                        String text = item.getText().toString();
//                        etInputAdd.setText(text);
//                    }
//                }
            }
        });
        findViewById(R.id.kbtAnalysisAdd).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {           // 分析账号密码
                String input = etInputAdd.getText().toString();
                MLOG("inputA "+input);
                mBDbsAccount = new ArrayList<>();
                if (!MAPI.isEmpty(input)) {
                    String text = input.replace("    ", "\n");
                    String[] gpLocal_1 = text.split("\n");
                    for (int index = 0; index < gpLocal_1.length; index++) {
                        text = gpLocal_1[index].replace("--", ",");
                        text = text.replace("--", ",");
                        text = text.replace("-", ",");
                        text = text.replace("，", ",");
                        text = text.replace("  ", ",");
                        text = text.replace("  ", ",");
                        text = text.replace(",,", ",");
                        text = text.replace(",,", ",");
                        String[] source = text.split(",");
                        if (source.length >= 2){
                            BDbsAccount bDbsAccount = new BDbsAccount();
                            for (int counter = 0; counter < source.length; counter++) {
                                if (source[counter].length() > 1) {
                                    bDbsAccount.AccountName = getAlphanumeric(source[counter]);
                                    if ((counter+1 < source.length) && source[counter+1].length() > 0) {
                                        bDbsAccount.Password = getAlphanumeric(source[counter+1]);
                                        break;
                                    }
                                }
                            }
                            bDbsAccount.SourceText = source;
                            bDbsAccount.WorksType = gWorksType;
                            if (!MAPI.isEmpty(bDbsAccount.AccountName) && !MAPI.isEmpty(bDbsAccount.Password)){
                                mBDbsAccount.add(bDbsAccount);
                            }
                        }
                    }
                }
                if (mBDbsAccount.size() > 0) {
                    int length = mBDbsAccount.size();
                    String text = "";
                    for (int index = 0; index < length; index++) {
                        BDbsAccount bDbsAccount = mBDbsAccount.get(index);
                        String appName = gsAppName;
                        text += String.format("%s、%s   %s   %s\n", index, appName, bDbsAccount.AccountName, bDbsAccount.Password);
                    }
                    MSKIN.setText(text, tvAnalysisAdd);
                }else {
                    MTOAST("请输入正确的账号及密码组合");
                }

            }
        });
        kbtEnterAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                                           // 确认添加账号
                addTask();
            }
        });
        findViewById(R.id.tvEnterAdd).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                         // 确认添加账号
                addTask();
            }
        });


        byte[] worksTypes = MAPP.makeArrayType(MSKIN.getStringArray(R.array.task_works_type));
        if (gWorksType == 33 || gWorksType == 49){
            cbAddTo[0].setText("同时添加到 唱吧K歌");
            cbAddTo[1].setText("同时添加到 唱吧图片");
            for (int index = 0; index < 2; index++) {
                if (gWorksType == worksTypes[index]){
                    cbAddTo[index].setChecked(true);
                }else {
                    boolean checked = MSKIN.getMemoryBoolean(W.AddToType33 + index, false);
                    cbAddTo[0].setChecked(checked);
                }
            }
            cbAddTo[1].setChecked(true);
            for (int index = 2; index < cbAddTo.length; index++){
                cbAddTo[index].setVisibility(View.GONE);
            }
        }else if (gWorksType < 32){
//            String[] texts = MSKIN.getStringArray(R.array.task_full_name);
            for (int index = 0; index < cbAddTo.length; index++){
                if (gWorksType == worksTypes[index]){
                    cbAddTo[index].setChecked(true);
                }else {
                    boolean checked = MSKIN.getMemoryBoolean(W.AddToType32 + index, false);
                    cbAddTo[index].setChecked(checked);
                }
                cbAddTo[index].setText(String.format("同时添加到 %s", MAPP.mWorksName[worksTypes[index]]));
            }
//cbAddTo[2].setChecked(false);cbAddTo[3].setChecked(false);cbAddTo[4].setChecked(false);cbAddTo[5].setChecked(false);
        }
    }
    @Override
    public void onInitData(){                                                                       // onInitView结束，开始加载数据
            MAPP.setTaskPause(true);

    }
    private void addTask(){
        if (mBDbsAccount == null || mBDbsAccount.size() < 1){
            MTOAST("先组合及分析账号密码");
            return;
        }
        if (kbtEnterAdd.getProgress() != 2) {
            kbtEnterAdd.setProgress(2);
            createAccount();
        }else {
            MTOAST("已经在增加之中，请稍候");
        }

    }

    @Override
    public void onFinish() {       // 使用者选择性继承，用户按了后退键，不继承就直接关闭了
//        MAPP.mAccount33 = null;
        MAPP.mSearch = null;
        MAPP.setTaskPause(false);
        setClose();
    }
    private String getArray(List<String> lists, String[] strings, int tick){
        String text;
        for (int index = 0; index < strings.length; index++){
            int flag = index % 32;
            if (((1<<flag) & tick) != 0){
                text = strings[index];
            }

        }
        return null;
    }

    private String getTabComment(@ArrayRes int id, int number){
        String[] strings = MSKIN.getStringArray(id);
        List<String> lists = new ArrayList<>();
        Random random = new Random();
        for (int index = 0; index < strings.length; index++){
            int flag = index % 16;
            if (flag == 0) {
                number = random.nextInt();
            }
            if (((1<<flag) & number) != 0){
                lists.add(strings[index]);
            }
        }
        StringBuffer stringBuffer = new StringBuffer();
        int length = lists.size();
        for (int index = 0; index < length; index++) {
            stringBuffer.append(lists.get(index));
            stringBuffer.append("\n");
        }
        return stringBuffer.toString();
//        return lists.toArray(new String[lists.size()]);
    }


    private void createAccount(){
        new TaskFree(null, new TaskFree.Listener() {
            @Override
            public void onMessage(boolean isThread, Object object) {
                if (isThread) {
                    int length = mBDbsAccount.size();
                    String tabAutoComment[] = {
                            "很棒，很棒","赞,好赞,太赞","完美挖，给力","要的就是这种感觉","很给力，赞赞赞赞", "支持你来啦", "我来了，支持。嘎嘎",
                    };
                    String tabNewComment[] = {
                            "支持新作品","赞,好赞,太赞","完美新作。支持到底","又来新作，厉害，加油加油","很厉害。新作无敌。赞赞赞赞在哪在哪在哪",
                    };
                    String tabOldComment[] = {
                            "很久没有你的作品了","最近很忙？都没有新作品",
                    };
                    String tabCareText[] = {
                            "今天开始做你的铁粉", "我要做你的铁粉", "关注你了",
                    };
                    String tabGiftText[] = {
                            "小小礼物，不成敬意", "只是一点小小的礼物",
                    };
                    String tabAdvertText[] = {
                            "做个小广告，可以关注我吗？", "这是广告，关注我吧",
                    };
                    mWorksType = MAPP.makeArrayType(MSKIN.getStringArray(R.array.task_works_type));
                    for (int counter = 0; counter < length; counter++) {
                        BDbsAccount bDbsAccount = mBDbsAccount.get(counter);
                        bDbsAccount.SetConfig = new int[6];                 // [0]间隔时间设置 [1]任务顺序 [2]黑名单保持的小时
                        Random random = new Random();
                        int number = Math.abs(random.nextInt());
                        bDbsAccount.SetConfig[0] = 27 + (number % 59);      // [0]间隔时间设置
                        bDbsAccount.SetConfig[1] = MDBS.getDbsId();         // [1]顺序
                        if (gWorksType == 33 || gWorksType == 49) {
                            bDbsAccount.SetConfig[2] = 24;                  // [2]不重新刷的黑名单保持的48小时
                        }else {
                            bDbsAccount.SetConfig[2] = 1;                   // [2]不重新刷的黑名单保持的1小时
                        }
                        bDbsAccount.SetConfig[3] = 48;                      // [3]黑名单最多的数量，会自动删除超出时间的数据
                        bDbsAccount.Status = "未登录";
                        bDbsAccount.UserName = "需要先登录";
                        bDbsAccount.WorksType = gWorksType;

                        bDbsAccount.TextFrist = new String[8];
                        bDbsAccount.TextComment = new String[8];            // [0]标准评论文字[1]第二评论文字[2]第二评论文字[3]旧作品[4]新作品[5]关注文字[6]礼物文字[7]广告文字

                        bDbsAccount.TextFrist[0] = MAPP.textsToText(tabAutoComment);       // [0]标准评论文字
                        bDbsAccount.TextComment[0] = MAPP.textsToText(tabAutoComment);     // [0]标准评论文字
                        bDbsAccount.TextFrist[3] = MAPP.textsToText(tabOldComment);       // [3]旧作品
                        bDbsAccount.TextComment[3] = MAPP.textsToText(tabOldComment);     // [3]旧作品
                        bDbsAccount.TextFrist[4] = MAPP.textsToText(tabNewComment);       // [4]新作品
                        bDbsAccount.TextComment[4] = MAPP.textsToText(tabNewComment);     // [4]新作品
                        bDbsAccount.TextFrist[5] = MAPP.textsToText(tabCareText);           // [5]关注文字
                        bDbsAccount.TextComment[5] = MAPP.textsToText(tabCareText);        // [5]关注文字
                        bDbsAccount.TextFrist[6] = MAPP.textsToText(tabGiftText);          // [6]礼物文字
                        bDbsAccount.TextComment[6] = MAPP.textsToText(tabGiftText);        // [6]礼物文字
                        bDbsAccount.TextFrist[7] = MAPP.textsToText(tabAdvertText);       // [7]广告文字
                        bDbsAccount.TextComment[7] = MAPP.textsToText(tabAdvertText);     // [7]广告文字
                        MAPP.MTOAST("正在添加 "+bDbsAccount.AccountName);
                        for (int index = 0; index < cbAddTo.length; index++){
                            if (gWorksType < 32) {
                                MSKIN.setMemoryBoolean(W.AddToType32 + index, cbAddTo[index].isChecked(), false);
                                if (cbAddTo[index].isChecked()) {
                                    bDbsAccount.WorksType = mWorksType[index];
                                    if (bDbsAccount.WorksType == AWorksType.WORKS_SING_SONG) {
//                            bDbsAccount.NormalComment = getTabCommentSingSong(number);
                                        bDbsAccount.TextFrist[0] = getTabComment(R.array.tab_comment_sing_song, number);
                                        bDbsAccount.TextComment[0] = bDbsAccount.TextFrist[0];
                                    } else if (bDbsAccount.WorksType == AWorksType.WORKS_RECITATION) {
//                            bDbsAccount.NormalComment = getTabCommentSingSong(number);
                                        bDbsAccount.TextFrist[0] = getTabComment(R.array.tab_comment_recite, number);
                                        bDbsAccount.TextComment[0] = bDbsAccount.TextFrist[0];
                                    } else if (bDbsAccount.WorksType == AWorksType.WORKS_OBB_RECITE) {
//                            bDbsAccount.NormalComment = getTabCommentSingSong(number);
                                        bDbsAccount.TextFrist[0] = getTabComment(R.array.tab_comment_obb_recite, number);
                                        bDbsAccount.TextComment[0] = bDbsAccount.TextFrist[0];
                                    }
                                    addBDbsAccount(bDbsAccount);
                                }
                            }else if (gWorksType == 33 || gWorksType == 49){
                                MSKIN.setMemoryBoolean(W.AddToType33+index, cbAddTo[index].isChecked(), false);
                                if (cbAddTo[index].isChecked()) {
                                    if (index == 0) {
                                        bDbsAccount.WorksType = 33;
                                        bDbsAccount.TextFrist[0] = getTabComment(R.array.tab_comment_sing_song, number);
                                        bDbsAccount.TextComment[0] = bDbsAccount.TextFrist[0];
                                    } else {
                                        bDbsAccount.WorksType = 49;
                                    }
                                    addBDbsAccount(bDbsAccount);
                                }
                            }else {
                                addBDbsAccount(bDbsAccount);
                            }
                        }
                    }
                    List<BDbsAccount> lists = MDBS.getBDbsAccount(gWorksType);
                    MLOG("listsA "+lists );
                    return;
                }
                setPageResult(mBDbsAccount);
                onFinish();
            }
        });

    }
    private void addBDbsAccount(BDbsAccount bDbsAccount){
        EditUtils editUtils = new EditUtils();
        bDbsAccount.CrcSum5 = editUtils.getCrcSum5(bDbsAccount.AccountName);
        bDbsAccount.CloneAppType = bDbsAccount.WorksType;
        if (MAPP.mManageAccount != null){
            App32.setUser(MAPP.mManageAccount.LoginFlag, (byte) 0);
        }
        String result = WorksQueue.getKgAppDbsKey(bDbsAccount, MDBS.SVR_LOGIN, false);    // 先从本地找相同的账号
        MLOG(String.format("KgAppDbsA B1 %s %08x", result, bDbsAccount.CrcSum5));
        if (!MAPI.isEmpty(result)){
            for (int index = 0; index < mWorksType.length; index++) {
                BDbsAccount account = MDBS.getBDbsAccount(mWorksType[index], bDbsAccount.AccountName);
                if (account != null && result.equals(account.LoginFlag)){    // 找到已经成功的
                    MLOG(String.format("KgAppDbsA B2 %s", result));
                    editUtils.copyBDbsAccount(bDbsAccount, account);
                    MDBS.setBDbsAccount(bDbsAccount);                       // 从本地找到相同的账号
                    return;
                }
            }
        }
        MAPP.MTOAST("正在从服务器找记录 "+bDbsAccount.AccountName);
        result = WorksQueue.getKgAppDbsKey(bDbsAccount, MDBS.SVR_LOGIN, true);    // 试试从服务器找相同的账号
//        MLOG(String.format("KgAppDbsA B5 %s %08x", result, bDbsAccount.CrcSum5));
        if (!MAPI.isEmpty(result)){
            String[] split = result.split(":");
            if (split.length >= 4 && split[2].equals(bDbsAccount.AccountName)) {
                bDbsAccount.UserIdS = split[0];
                bDbsAccount.UserID = MAPI.STRING_DEC32(split[0]);
                bDbsAccount.LoginFlag = String.format("%s:%s", split[0], split[1]);
                bDbsAccount.UserName = split[3];
                bDbsAccount.Status = "ok";
                MLOG(String.format("KgAppDbsA B6 %s %08x", result, bDbsAccount.CrcSum5));
            }else {
                MLOGE(String.format("KgAppDbsA Error %s(%s)%s", split.length, bDbsAccount.AccountName, split[2]));
            }
        }
        MDBS.setBDbsAccount(bDbsAccount);
    }

    private String getAlphanumeric(String text){
        int length = text.length();
        StringBuffer stringBuffer = new StringBuffer();
        boolean found = false;
        for (int index = 0; index < length; index++) {
            char temp = text.charAt(index);
            if ((temp >= '0' && temp <= '9') || (temp >= 'a' && temp <= 'z') || (temp >= 'A' && temp <= 'Z')){
                stringBuffer.append(temp);
                found = true;
            }else if (found){
                break;
            }
        }
        return stringBuffer.toString();
    }

}

